package com.itheima.controller;

import com.itheima.pojo.Employee;
import com.itheima.pojo.R;
import com.itheima.pojo.UserDto;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @RestController   与 @Controller 区别
 *  @Controller  +  @ResponseBody
 *  @Controller   LoginController 变成一个spring bean 可以用来处理请求
 *  @ResponseBody   把对象转换程JSON返回给前端  User
 */
@Controller
@ResponseBody
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private HttpServletRequest httpServletRequest;

    @PostMapping("/employee/login")
    //{"username":"admin","password":"123456"}
    //@RequestBody 请求JSON转对象
    //@ResponseBody 响应对象转JSON
    public R loginUser(@RequestBody UserDto user){
        //1.校验参数是否存在
        if(user == null){
            return R.error("参数非法");
        }
        R r = userService.loginUser(user);
        Employee data = (Employee) r.getData();
        if(data != null){
            HttpSession session = httpServletRequest.getSession();
            session.setAttribute("userId",data.getId());
        }
        return r;
    }
}
